#include <rclcpp/rclcpp.hpp>
#include "base_interface_demo01/srv/add_int.hpp"
using namespace std::chrono_literals;
using base_interface_demo01::srv::AddInt;
class ClientService: public rclcpp::Node
{
 public:
    ClientService():Node("client_srv_node_cpp")
    {
        RCLCPP_INFO(this->get_logger(),"创建客户端节点");
        this->client_ = this->create_client<AddInt>("add_int");
    }
public:
    bool connect_server()
    {
        while (!this->client_->wait_for_service(1s))
        {
            //判断程序是否正常执行中 ctrl+c 可以导致不正常执行
            //ctrl+c 导致context 失效 释放资源，关闭了context.所以无法获取logger this->get_logger不行
            if(!rclcpp::ok())
            {
                RCLCPP_INFO(rclcpp::get_logger("rclcpp"),"强行中断客户端");
                return false;
            }
            RCLCPP_INFO(rclcpp::get_logger("rclcpp"),"服务连接中");
        }
        return true;
    }
    rclcpp::Client<AddInt>::FutureAndRequestId send_request(int num1,int num2)
    {
        
        auto request=std::make_shared<AddInt::Request>();
        request->num1=num1;
        request->num2=num2;
        return client_->async_send_request(request);
    }
private:
    rclcpp::Client<AddInt>::SharedPtr client_;      

};
int main(int argc, char ** argv)
{
    if (argc!=3)
    {
        RCLCPP_ERROR(rclcpp::get_logger("rclcpp"),"请提交两个整形数字");
        return 1;
    }
    rclcpp::init(argc,argv);
    auto srv_client = std::make_shared<ClientService>();
    if(srv_client->connect_server())
    {
        auto future = srv_client->send_request(atoi(argv[1]), atoi(argv[2]));
        //处理的情况 有三种 稍显复杂
        if(rclcpp::spin_until_future_complete(srv_client,future)==rclcpp::FutureReturnCode::SUCCESS)
        {
            RCLCPP_INFO(srv_client->get_logger(),"响应成功！ sum= %d",future.get()->sum);
        }
        else
        {
            RCLCPP_INFO(srv_client->get_logger(),"响应失败");
        }
    }
    else
    {
        RCLCPP_ERROR(rclcpp::get_logger("rclcpp"),"服务器链接失败 程序推出！");
        return 0;
    }
    rclcpp::shutdown();
    return 0;
}